/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) QuerydslKt.java 2018-08-21 20:31
 */

package cn.jh.common.core.data.repository;

import com.google.common.collect.BoundType;
import com.google.common.collect.Range;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.DateTimePath;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.google.common.base.Preconditions.checkArgument;


/**
 * @author Fuchun
 * @since 1.0
 */
public class QuerydslKt {

    public static BooleanExpression buildDateTimeClause(
            DateTimePath<LocalDateTime> path, Range<LocalDateTime> range) {
        checkArgument(range != null &&
                (range.hasLowerBound() || range.hasUpperBound()),
                "The range must be a bounded.");
        if (range.isEmpty()) {
            return path.eq(range.lowerEndpoint());
        }
        LocalDateTime from = null, to = null;
        if (range.hasLowerBound()) {
            from = range.lowerEndpoint();
            if (range.lowerBoundType() == BoundType.OPEN) {
                from = from.plusSeconds(1L);
            }
        }
        if (range.hasUpperBound()) {
            to = range.upperEndpoint();
            if (range.upperBoundType() == BoundType.OPEN) {
                to = to.minusSeconds(1L);
            }
        }
        if (from == null && to == null) {
            // never
            throw new IllegalArgumentException("The range must be a bounded.");
        } else if (Objects.equals(from, to)) {
            return from != null ? path.eq(from) : path.eq(to);
        }
        return path.between(from, to);
    }
}
